using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesClaimsPendingForAuthorizedDetail : System.Web.UI.Page
{
    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected GonzalesClaimHeader ResultObj = null;
    protected readonly int TotalColumns = 20;
    protected bool IsApprove = true;
    protected decimal TotalPersonalExpenses = 0;

    #region ClaimHavingCreditCard
    protected bool ClaimHavingCreditCard
    {
        get
        {
            return (bool)ViewState["ClaimHavingCreditCard"];
        }

        set
        {
            ViewState["ClaimHavingCreditCard"] = value;
        }
    }
    #endregion

    #region ClaimInternalID
    protected string ClaimInternalID
    {
        get
        {
            return ViewState["ClaimInternalID"].ToString();
        }

        set
        {
            ViewState["ClaimInternalID"] = value;
        }
    }

    #endregion

    #region WeeklySpentPolicies
    protected WeeklyTotalSpentPolicies WeeklySpentPolicies
    {
        get
        {
            return (WeeklyTotalSpentPolicies)ViewState["WeeklyTotalSpentPolicies"];
        }

        set
        {
            ViewState["WeeklyTotalSpentPolicies"] = value;
        }
    }
    #endregion

    #region Common Variables for Language Translation

    #region ItemExpenseDetail
    protected string ItemExpenseDetail
    {
        get
        {
            return ViewState["ItemExpenseDetail"].ToString();
        }

        set
        {
            ViewState["ItemExpenseDetail"] = value;
        }
    }
    #endregion

    #region ItemRemarks
    protected string ItemRemarks
    {
        get
        {
            return ViewState["ItemRemarks"].ToString();
        }

        set
        {
            ViewState["ItemRemarks"] = value;
        }
    }
    #endregion

    #region ItemDate
    protected string ItemDate
    {
        get
        {
            return ViewState["ItemDate"].ToString();
        }

        set
        {
            ViewState["ItemDate"] = value;
        }
    }
    #endregion

    #region ItemDateEnd
    protected string ItemDateEnd
    {
        get
        {
            return ViewState["ItemDateEnd"].ToString();
        }

        set
        {
            ViewState["ItemDateEnd"] = value;
        }
    }
    #endregion

    #region ItemLocation
    protected string ItemLocation
    {
        get
        {
            return ViewState["ItemLocation"].ToString();
        }

        set
        {
            ViewState["ItemLocation"] = value;
        }
    }
    #endregion

    #region ItemClaimed
    protected string ItemClaimed
    {
        get
        {
            return ViewState["ItemClaimed"].ToString();
        }

        set
        {
            ViewState["ItemClaimed"] = value;
        }
    }
    #endregion

    #region ItemTax
    protected string ItemTax
    {
        get
        {
            return ViewState["ItemTax"].ToString();
        }

        set
        {
            ViewState["ItemTax"] = value;
        }
    }
    #endregion

    #region ItemExCurrency
    protected string ItemExCurrency
    {
        get
        {
            return ViewState["ItemExCurrency"].ToString();
        }

        set
        {
            ViewState["ItemExCurrency"] = value;
        }
    }
    #endregion

    #region ItemExRate
    protected string ItemExRate
    {
        get
        {
            return ViewState["ItemExRate"].ToString();
        }

        set
        {
            ViewState["ItemExRate"] = value;
        }
    }
    #endregion

    #region ItemLocalAmount
    protected string ItemLocalAmount
    {
        get
        {
            return ViewState["ItemLocalAmount"].ToString();
        }

        set
        {
            ViewState["ItemLocalAmount"] = value;
        }
    }
    #endregion

    #region ItemTooltipsReceipt
    protected string ItemTooltipsReceipt
    {
        get
        {
            return ViewState["ItemTooltipsReceipt"].ToString();
        }

        set
        {
            ViewState["ItemTooltipsReceipt"] = value;
        }
    }
    #endregion

    #region ItemProjectID
    protected string ItemProjectID
    {
        get
        {
            return ViewState["ItemProjectID"].ToString();
        }

        set
        {
            ViewState["ItemProjectID"] = value;
        }
    }
    #endregion

    #region ItemChargeToProfitCenter
    protected string ItemChargeToProfitCenter
    {
        get
        {
            return ViewState["ItemChargeToProfitCenter"].ToString();
        }

        set
        {
            ViewState["ItemChargeToProfitCenter"] = value;
        }
    }
    #endregion

    #region ItemChargeToEmployeeID
    protected string ItemChargeToEmployeeID
    {
        get
        {
            return ViewState["ItemChargeToEmployeeID"].ToString();
        }

        set
        {
            ViewState["ItemChargeToEmployeeID"] = value;
        }
    }
    #endregion

    #region ItemDetail
    protected string ItemDetail
    {
        get
        {
            return ViewState["ItemDetail"].ToString();
        }

        set
        {
            ViewState["ItemDetail"] = value;
        }
    }
    #endregion

    #region ItemApprove
    protected string ItemApprove
    {
        get
        {
            return ViewState["ItemApprove"].ToString();
        }

        set
        {
            ViewState["ItemApprove"] = value;
        }
    }
    #endregion

    #region AltNoDetail
    protected string AltNoDetail
    {
        get
        {
            return ViewState["AltNoDetail"].ToString();
        }

        set
        {
            ViewState["AltNoDetail"] = value;
        }
    }
    #endregion

    #region ItemTooltipApproverRemarks
    protected string ItemTooltipApproverRemarks
    {
        get
        {
            return ViewState["ItemTooptipApproverRemarks"].ToString();
        }

        set
        {
            ViewState["ItemTooptipApproverRemarks"] = value;
        }
    }
    #endregion

    #region SortOrderASC
    protected string SortOrderASC
    {
        get
        {
            return ViewState["SortOrderASC"].ToString();
        }

        set
        {
            ViewState["SortOrderASC"] = value;
        }
    }
    #endregion

    #region SortOrderDESC
    protected string SortOrderDESC
    {
        get
        {
            return ViewState["SortOrderDESC"].ToString();
        }

        set
        {
            ViewState["SortOrderDESC"] = value;
        }
    }
    #endregion

    #region AuthorizedMessage
    protected string AuthorizedMessage
    {
        get
        {
            return ViewState["AuthorizedMessage"].ToString();
        }

        set
        {
            ViewState["AuthorizedMessage"] = value;
        }
    }
    #endregion

    #region ReceiptNo
    protected string ReceiptNo
    {
        get
        {
            return ViewState["ReceiptNo"].ToString();
        }

        set
        {
            ViewState["ReceiptNo"] = value;
        }
    }
    #endregion

    #region CreditCardDetails
    protected string CreditCardDetails
    {
        get
        {
            return ViewState["CreditCardDetails"].ToString();
        }

        set
        {
            ViewState["CreditCardDetails"] = value;
        }
    }
    #endregion

    #region AuthorizerRemarks
    protected string AuthorizerRemarks
    {
        get
        {
            return ViewState["AuthorizerRemarks"].ToString();
        }

        set
        {
            ViewState["AuthorizerRemarks"] = value;
        }
    }
    #endregion

    #region MandatoryMessage
    protected string MandatoryMessage
    {
        get
        {
            return ViewState["MandatoryMessage"].ToString();
        }

        set
        {
            ViewState["MandatoryMessage"] = value;
        }
    }
    #endregion

    #region WarningMessage1
    protected string WarningMessage1
    {
        get
        {
            return ViewState["WarningMessage1"].ToString();
        }

        set
        {
            ViewState["WarningMessage1"] = value;
        }
    }
    #endregion

    #region WarningMessage2
    protected string WarningMessage2
    {
        get
        {
            return ViewState["WarningMessage2"].ToString();
        }

        set
        {
            ViewState["WarningMessage2"] = value;
        }
    }
    #endregion

    #endregion

    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        if (!IsPostBack)
        {
            #region Request.QueryString["id"]

            if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36)
            {
                this.ClaimInternalID = Request.QueryString["id"];
            }
            else
            {
                Response.Redirect(GonzalesErrorPageRedirect.PageFlowError);
            }

            #endregion
            
            this.ClaimHavingCreditCard = false;

            this.SwitchLanguage();
            this.PageComponentSetup();
        }

        // every load muz read
        this.LoadData();

        if (this.ResultObj != null)
        {
            if (!IsPostBack)
            {
                this.FillInData();
            }

            #region Table Grid

            this.BuiltTable();

            for (int x = 0; x < this.ResultObj.ClaimDetails.Count; x++)
            {
                GonzalesClaimItemWithWeeklyLimit CurClaimItem = (GonzalesClaimItemWithWeeklyLimit)this.ResultObj.ClaimDetails[x];
                this.ClaimHavingCreditCard = (CurClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard) ? true : this.ClaimHavingCreditCard;

                this.BuiltRow((x+1), CurClaimItem);    // this is for row building
            }

            #endregion

            #region hide the credit card and personal
            if (!this.ClaimHavingCreditCard)
            {
                for (int x = 0; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
                {
                    this.Table_ClaimDetailGrid.Rows[x].Cells[2].Visible = this.Table_ClaimDetailGrid.Rows[x].Cells[3].Visible = false;
                }
            }
            #endregion

            this.PolicyEnvironmentSetup();
            //this.DataValidateByPolicy();

        }
        this.LabelValue_TotalPersonalExpenses.Text = TotalPersonalExpenses.ToString(GonzalesGeneralVariables.CurrencyFormat);
        this.Label_TotalLocalAmount.Text = (this.ResultObj.TotalClaimedAmount - TotalPersonalExpenses).ToString(GonzalesGeneralVariables.CurrencyFormat);

        this.ShadowUserPolicy();
    }
    #endregion

    #region DropDownList_SortBy_SelectedIndexChanged
    protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
    {        
        if (this.ResultObj != null)
        {
            if (this.DropDownList_SortBy.SelectedIndex == 0)
            {
                // original order

                for (int x = (this.Table_ClaimDetailGrid.Rows.Count - 1); x > 1; x--)
                {
                    for (int y = 1; y < x; y++)
                    {
                        int Order1 = Int32.Parse(((HiddenField)this.Table_ClaimDetailGrid.Rows[y].Cells[18].Controls[2]).Value);
                        int Order2 = Int32.Parse(((HiddenField)this.Table_ClaimDetailGrid.Rows[y + 1].Cells[18].Controls[2]).Value);

                        if (Order1 > Order2)
                        {
                            TableRow Tmp1 = this.Table_ClaimDetailGrid.Rows[y];

                            this.Table_ClaimDetailGrid.Rows.RemoveAt(y);
                            this.Table_ClaimDetailGrid.Rows.AddAt(y + 1, Tmp1);
                        }
                    }
                }

            }
            else if (this.DropDownList_SortBy.SelectedIndex == 1)
            {
                // expense detail

                for (int x = (this.Table_ClaimDetailGrid.Rows.Count - 1); x > 1; x--)
                {
                    for (int y = 1; y < x; y++)
                    {
                        if (this.Table_ClaimDetailGrid.Rows[y].Cells[1].Text.CompareTo(this.Table_ClaimDetailGrid.Rows[y + 1].Cells[1].Text) > 0)
                        {
                            TableRow Tmp1 = this.Table_ClaimDetailGrid.Rows[y];

                            this.Table_ClaimDetailGrid.Rows.RemoveAt(y);
                            this.Table_ClaimDetailGrid.Rows.AddAt(y + 1, Tmp1);
                        }
                    }
                }

            }
            else if (this.DropDownList_SortBy.SelectedIndex == 2)
            {
                // claim date

                for (int x = (this.Table_ClaimDetailGrid.Rows.Count - 1); x > 1; x--)
                {
                    for (int y = 1; y < x; y++)
                    {
                        DateTime DateTime1 = SwissArmy.DateConvert(this.Table_ClaimDetailGrid.Rows[y].Cells[6].Text, this.CurrentPrivateSession.DateFormatInUse);
                        DateTime DateTime2 = SwissArmy.DateConvert(this.Table_ClaimDetailGrid.Rows[y + 1].Cells[6].Text, this.CurrentPrivateSession.DateFormatInUse);

                        if (DateTime1 > DateTime2)
                        {
                            TableRow Tmp1 = this.Table_ClaimDetailGrid.Rows[y];                            

                            this.Table_ClaimDetailGrid.Rows.RemoveAt(y);
                            this.Table_ClaimDetailGrid.Rows.AddAt(y + 1, Tmp1);
                        }
                    }
                }
            }
        }
        
    }
    #endregion

    #region Button_Approve_Click
    protected void Button_Approve_Click(object sender, EventArgs e)
    {
        if (this.DataValidate("approved"))
        {
            this.DataCollect();

            if (IsApprove)
            {
                this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.PendingForFinanceVerification;
                this.ResultObj.AuthorizedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;                
                this.ResultObj.LastUpdatedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                this.ResultObj.AuthorizedOn = this.ResultObj.LastUpdatedOn = DateTime.Now;

                // no need to assign next finance admin
                // there will be more than 1 finance admin

                if (this.SaveData())
                {
                    // this is to monitor entire claim flow
                    this.CurLogManager.LogAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, GonzalesUserAction.ClaimAuthorized, this.ResultObj.Status);

                    //Added By Agnes [16th Aug, 2011]
                    CurLogManager.UpdateLogAuthorizerClaimAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName, ClaimManager.GetClaimStatusInString(this.ResultObj.Status));

                    // redirect
                    Response.Redirect("GonzalesClaimsPendingForAuthorized.aspx");
                }
            }
            else
            {
                // is approve suppose to be true!
                this.ShowErrorMessage(this.AuthorizedMessage);
            }
        }

    }
    #endregion

    #region Button_Reject_Click
    protected void Button_Reject_Click(object sender, EventArgs e)
    {
        if (this.DataValidate("reject"))
        {
            this.DataCollect();

            //if (!IsApprove)
            //{
                this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.RejectedByAuthorizer;

                this.ResultObj.LastUpdatedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                this.ResultObj.LastUpdatedOn = DateTime.Now;

                if (this.SaveData())
                {
                    #region Send email
                    if (this.ResultObj.ClaimedBy.DisplayName.CompareTo("Brian Douglas King") != 0)
                    {
                        if (GonzalesGeneralVariables.EmailActive)
                        {
                            string MailContent = "", MailTitle = "";
                            SystemUser Receiver = null;
                            SystemUser Authorizer = null;

                            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                            {
                                Receiver = CurUserManager.GetUserByInternalID(this.ResultObj.ClaimedBy.InternalID);
                            }

                            #region Send email back to claimant
                            if (Receiver != null && Receiver.DisplayName.CompareTo("Brian Douglas King") != 0)
                            {
                                using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimRejected, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                {
                                    MailContent = CurMailGenerator.GenerateRejectedClaimForClaimant(
                                        Receiver.DisplayName,
                                        Receiver.EmployeeID,
                                        Receiver.EmailID,
                                        Receiver.FromCompany.CompanyName,
                                        this.ResultObj.ClaimID,
                                        this.ResultObj.Reasons,
                                        this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                        ClaimManager.GetClaimStatusInString(this.ResultObj.Status) + " - " + this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName,
                                        GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.REJECTED_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + Receiver.EmailID);

                                    MailTitle = CurMailGenerator.MailTitle;
                                }
                            }

                            if (MailContent != null)
                            {
                                using (EmailFactory CurEmailFactory = new EmailFactory(
                                    Receiver.DisplayName,
                                    Receiver.Email,
                                    MailTitle,
                                    MailContent))
                                {
                                    if (!CurEmailFactory.SendNow())
                                    {
                                        string LogID = SwissArmy.UniqueID();
                                        this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForAuthorizedDetail.Button_Reject_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                    }
                                }
                            }
                            #endregion

                            #region Send mails back to previous approver

                            LogsCollection ActionLogCollection = null;
                            ActionLogCollection = this.CurLogManager.GetActionLogByClaimID(this.ClaimInternalID);

                            if (ActionLogCollection != null)
                            {
                                for (int x = 0; x < ActionLogCollection.Count; x++)
                                {
                                    ActionLogItem CurLogItem = (ActionLogItem)ActionLogCollection[x];

                                    // only pick those approved and authorized
                                    if (CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.Approved ||
                                        CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.Escalated ||
                                        CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.Authorized ||
                                        CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.PendingForAuthorize ||
                                        CurLogItem.ActionStatus == GonzalesClaimHeader.TypeOfClaimStatus.PendingForFinanceVerification)
                                    {
                                        using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                                        {
                                            Authorizer = CurUserManager.GetUserByInternalID(CurLogItem.LoggedBy.InternalID);

                                            if (Authorizer != null && Authorizer.DisplayName.CompareTo("Brian Douglas King") != 0)
                                            {
                                                using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimRejectedNotifyApprover, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                                {
                                                    MailContent = CurMailGenerator.GenerateRejectedClaimForPreviousApprover(
                                                        Receiver.DisplayName,
                                                        Receiver.EmployeeID,
                                                        Receiver.EmailID,
                                                        Receiver.FromCompany.CompanyName,
                                                        this.ResultObj.ClaimID,
                                                        this.ResultObj.Reasons,
                                                        this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                                        ClaimManager.GetClaimStatusInString(this.ResultObj.Status) + " - " + Authorizer.DisplayName,
                                                        GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.REJECTEDNOTIFYAPPR_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + Receiver.EmailID,
                                                        CurLogItem.LogDate.ToLongDateString());

                                                    MailTitle = CurMailGenerator.MailTitle;
                                                }

                                                if (MailContent != null)
                                                {
                                                    using (EmailFactory CurEmailFactory = new EmailFactory(
                                                        Authorizer.DisplayName,
                                                        Authorizer.Email,
                                                        MailTitle,
                                                        MailContent))
                                                    {
                                                        if (!CurEmailFactory.SendNow())
                                                        {
                                                            string LogID = SwissArmy.UniqueID();
                                                            this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Reject_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                string LogID = SwissArmy.UniqueID();
                                                this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.Button_Reject_Click] : Failed at CurUserManager.GetUserByInternalID('" + CurLogItem.LoggedBy.InternalID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                            }   // if receiver != null
                                        } // user manager
                                    }


                                }
                            }

                            #endregion
                        }
                    }

                    #endregion
                    
                    // this is to monitor entire claim flow
                    this.CurLogManager.LogAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, GonzalesUserAction.ClaimRejectedByAuthorizer, this.ResultObj.Status);

                    //Added By Agnes [16th Aug, 2011]
                    CurLogManager.UpdateLogAuthorizerClaimAction(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName, ClaimManager.GetClaimStatusInString(this.ResultObj.Status));

                    // redirect to main page
                    Response.Redirect("GonzalesClaimsPendingForAuthorized.aspx");
                }
            //}
            //else
            //{
            //    // IsApprove suppose to be false!
            //    this.ShowErrorMessage("At least 1 item need to be reject in order to reject the entire claim");
            //}

        }
    }
    #endregion

    #region ImageButton_Cancel_Click
    protected void ImageButton_Cancel_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("GonzalesClaimsPendingForAuthorized.aspx");
    }

    #endregion


    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        //this.Label_TotalAmount.Text += " (" + this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency.InternalID + ")";
        this.Label_TotalLocalAmount.Text = " 0";

        //this.Button_Reject.Attributes["onclick"] = "return confirm('Are you sure?');";

        // sort order
        this.DropDownList_SortBy.Items.Add(new ListItem("Original Order", ""));
        this.DropDownList_SortBy.Items.Add(new ListItem(this.ItemExpenseDetail, "ExpenseDetail"));
        this.DropDownList_SortBy.Items.Add(new ListItem(this.ItemDate, "ClaimDate"));
        
        // cheque
        this.Table_ChequeInfo.Visible = false;

        // file upload
        this.Button_FileManager.Attributes["onclick"] = "ShowModal('FileManager', '', 'id=" + this.ClaimInternalID + "&NoEdit=1'); return false;";

        // printer friendly
        this.Button_PrinterFriendly.Attributes["onclick"] = "var windetail = window.open('GonzalesViewClaim.aspx?id=" + this.ClaimInternalID + "','','scrollbars=yes,width=800,height=600'); return false;";
        this.Button_PrinterFriendlyNameList.Attributes["onclick"] = "var windetail = window.open('GonzalesViewClaimNameList.aspx?id=" + this.ClaimInternalID + "','','scrollbars=yes,width=800,height=600'); return false;";

    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Remarks.Text = CurLanguageFactory.DisplayValue("Remarks");

                this.Label_EmployeeName.Text = CurLanguageFactory.DisplayValue("EmployeeName") + ":";
                this.Label_EmployeeNo.Text = CurLanguageFactory.DisplayValue("EmployeeNo") + ":";
                this.Label_Category.Text = CurLanguageFactory.DisplayValue("Category") + ":";
                this.Label_ClaimNum.Text = CurLanguageFactory.DisplayValue("ClaimID") + ":";
                this.Label_Purpose.Text = CurLanguageFactory.DisplayValue("Purpose") + ":";
                this.Label_CreationDate.Text = CurLanguageFactory.DisplayValue("CreationDate") + ":";
                this.Label_SubmissionDate.Text = CurLanguageFactory.DisplayValue("SubmissionDate") + ":";
                this.Label_ProfitCenter.Text = CurLanguageFactory.DisplayValue("ProfitCenter") + ":";
                this.Label_ClaimPeriod.Text = CurLanguageFactory.DisplayValue("ClaimPeriod");
                this.Label_TotalAmount.Text = CurLanguageFactory.DisplayValue("TotalAmount");
                this.Label_TotalAmountLessPaid.Text = CurLanguageFactory.DisplayValue("TotalAmountLessPaid");
                this.Label_OwningEmployee.Text = CurLanguageFactory.DisplayValue("OwningEmployee");
                this.Label_ChequeNo.Text = CurLanguageFactory.DisplayValue("ChequeNo");
                this.Label_IssuedBank.Text = CurLanguageFactory.DisplayValue("IssuedBank");

                this.Button_Approve.Text = CurLanguageFactory.DisplayValue("ButtonApprove");
                this.Button_Reject.Text = CurLanguageFactory.DisplayValue("ButtonReject");
                this.Button_FileManager.Text = CurLanguageFactory.DisplayValue("FileManager");
                this.Button_PrinterFriendly.Text = CurLanguageFactory.DisplayValue("PrinterFriendly");
                this.Button_PrinterFriendlyNameList.Text = CurLanguageFactory.DisplayValue("PrinterFriendlyNameList");

                this.AuthorizedMessage = CurLanguageFactory.DisplayValue("AuthorizedMessage");
                this.CreditCardDetails = CurLanguageFactory.DisplayValue("CreditCardDetails");
                this.ReceiptNo = CurLanguageFactory.DisplayValue("ReceiptNo");

                this.ItemExpenseDetail = CurLanguageFactory.DisplayValue("ItemExpenseDetail");
                this.ItemRemarks = CurLanguageFactory.DisplayValue("ItemRemarks");
                this.ItemDate = CurLanguageFactory.DisplayValue("ItemClaimedDate");
                this.ItemDateEnd = CurLanguageFactory.DisplayValue("ItemClaimedDateEnd");
                this.ItemLocation = CurLanguageFactory.DisplayValue("ItemLocation");
                this.ItemClaimed = CurLanguageFactory.DisplayValue("ItemClaimedAmount");
                this.ItemTax = CurLanguageFactory.DisplayValue("ItemTax");
                this.ItemExCurrency = CurLanguageFactory.DisplayValue("ItemExCurrency");
                this.ItemExRate = CurLanguageFactory.DisplayValue("ItemExRate");
                this.ItemLocalAmount = CurLanguageFactory.DisplayValue("ItemLocalAmount");
                this.ItemTooltipsReceipt = CurLanguageFactory.DisplayValue("ItemTooltipsReceipt");
                this.ItemProjectID = CurLanguageFactory.DisplayValue("ItemProjectID");
                this.ItemDetail = CurLanguageFactory.DisplayValue("ItemDetail");
                this.ItemApprove = CurLanguageFactory.DisplayValue("ItemApprove");
                this.ItemTooltipApproverRemarks = CurLanguageFactory.DisplayValue("ItemTooltipApproverRemarks");
                this.AuthorizerRemarks = CurLanguageFactory.DisplayValue("AuthorizerRemarks");
                this.WarningMessage1 = CurLanguageFactory.DisplayValue("WarningMessage1");
                this.WarningMessage2 = CurLanguageFactory.DisplayValue("WarningMessage2");
                this.MandatoryMessage = CurLanguageFactory.DisplayValue("MandatoryMessage");

                this.AltNoDetail = CurLanguageFactory.DisplayValue("AltNoDetail");

                this.Button_Approve.Attributes["onclick"] = "return confirm('" + CurLanguageFactory.DisplayValue("ApproveConfirmation") + "');";
                this.Button_Reject.Attributes["onclick"] = "return confirm('" + CurLanguageFactory.DisplayValue("RejectConfirmation") + "');";
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesClaimsPendingForAuthorizedDetail.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region BuiltTable
    protected void BuiltTable()
    {
        // add all the table header
        TableRow HeaderRow = new TableRow();

        for (int x = 0; x < this.TotalColumns; x++)
        {
            HeaderRow.Cells.Add(new TableCell());
            HeaderRow.Cells[x].CssClass = "GridViewHeader";
        }

        HeaderRow.Cells[0].Text = "No.";
        HeaderRow.Cells[1].Text = this.ItemExpenseDetail; HeaderRow.Cells[1].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[2].Text = "";
        HeaderRow.Cells[3].Text = "";
        HeaderRow.Cells[4].Text = this.ItemLocation; HeaderRow.Cells[4].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[5].Text = this.ReceiptNo; HeaderRow.Cells[5].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[6].Text = this.ItemDate; HeaderRow.Cells[6].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[7].Text = this.CreditCardDetails; HeaderRow.Cells[7].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[8].Text = this.ItemRemarks; HeaderRow.Cells[8].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[9].Text = this.ItemClaimed; HeaderRow.Cells[9].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[10].Text = this.ItemTax; HeaderRow.Cells[10].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[11].Text = this.ItemExCurrency; HeaderRow.Cells[11].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[12].Text = this.ItemExRate; HeaderRow.Cells[12].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[13].Text = this.ItemLocalAmount; HeaderRow.Cells[13].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[14].Text = "R"; HeaderRow.Cells[14].HorizontalAlign = HorizontalAlign.Center; HeaderRow.Cells[14].ToolTip = this.ItemTooltipsReceipt;
        HeaderRow.Cells[15].Text = this.ItemProjectID; HeaderRow.Cells[15].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[16].Text = "D"; HeaderRow.Cells[16].HorizontalAlign = HorizontalAlign.Center; HeaderRow.Cells[16].ToolTip = this.ItemDetail;
        HeaderRow.Cells[17].Text = "";

        // image for approve
        //Image Image_Approve = new Image();
        //Image_Approve.ImageUrl = GonzalesImages.Icon_Approve;
        //Image_Approve.ToolTip = this.ItemTooltipApproverRemarks;
        //HeaderRow.Cells[18].Controls.Add(Image_Approve);
        //HeaderRow.Cells[18].HorizontalAlign = HorizontalAlign.Center;


        //frank change imange to checkbox
        CheckBox ckApprove = new CheckBox();
        ckApprove.ID = "checkall";
        ckApprove.AutoPostBack = true;
        HeaderRow.Cells[18].Controls.Add(ckApprove);
        HeaderRow.Cells[18].HorizontalAlign = HorizontalAlign.Center;
        ckApprove.CheckedChanged += new EventHandler(ckApprove_CheckedChanged);

        HeaderRow.Cells[19].Text = this.AuthorizerRemarks; HeaderRow.Cells[19].HorizontalAlign = HorizontalAlign.Center;

        this.Table_ClaimDetailGrid.Rows.Add(HeaderRow);
    }
    void ckApprove_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chkAll = (CheckBox)Table_ClaimDetailGrid.FindControl("checkall");
        bool chkFlag = false;
        if (chkAll.Checked) chkFlag = true;
        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            CheckBox CheckBoxApprove = (CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[19].Controls[0];
            CheckBoxApprove.Checked = chkFlag;
        }

        //foreach (GridViewRow dr in Table_ClaimDetailGrid.Rows)
        //{
        //    CheckBox chk = (CheckBox)dr.Cells[0].FindControl("ckApprove");
        //    chk.Checked = chkFlag;
        //}
    }
    #endregion

    #region BuiltRow
    protected void BuiltRow(int RowIndex, GonzalesClaimItemWithWeeklyLimit CurrentClaimItem)
    {
        TableRow ItemRow = new TableRow();
        ItemRow.ID = CurrentClaimItem.InternalID;
        int CellCounter = 0;

        for (int x = 0; x < this.TotalColumns; x++)
        {
            ItemRow.Cells.Add(new TableCell());
            ItemRow.Cells[x].CssClass = "GridViewItem";
        }

        #region 0. No.

        ItemRow.Cells[CellCounter].Text = RowIndex.ToString();
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 1. Expense Detail / Claim Type

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.ClaimType.DisplayName;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Left;

        #endregion

        #region 2. claim detail type

        CellCounter++;

        if (CurrentClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard)
        {
            Image Image_CreditCard = new Image();
            Image_CreditCard.ImageUrl = GonzalesImages.Icon_CreditCard;                        

            ItemRow.Cells[CellCounter].Controls.Add(Image_CreditCard);
        }

        #endregion

        #region 3. Is Personal

        CellCounter++;

        if (CurrentClaimItem.IsPersonnal)
        {
            Image Image_IsPersonal = new Image();
            Image_IsPersonal.ImageUrl = GonzalesImages.Icon_Personal;

            ItemRow.Cells[CellCounter].Controls.Add(Image_IsPersonal);
        }

        #endregion

        #region 4. Country

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.Country.DisplayName;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 5. City

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.City;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 6. Date

        CellCounter++;        
        ItemRow.Cells[CellCounter].Text = SwissArmy.DateConvert(CurrentClaimItem.ClaimDate, this.CurrentPrivateSession.DateFormatInUse, "/");        
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 7. Description

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.Description;
        ItemRow.Cells[CellCounter].ToolTip = CurrentClaimItem.Description;

        #endregion

        #region 8. Remarks

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.Remarks;
        ItemRow.Cells[CellCounter].ToolTip = CurrentClaimItem.Remarks;

        #endregion

        #region 9. Claimed Amount

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.ClaimedAmount.ToString(GonzalesGeneralVariables.CurrencyFormat);
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 10. Tax / GST

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.Tax.ToString();
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Right;

        #endregion

        #region 11. Exchange Currency

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.ExchangeCurrency.DisplayName;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 12. Ex Rate

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = Convert.ToDecimal(CurrentClaimItem.ExchangeRate).ToString();
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        try
        {
            if (Convert.ToDecimal(CurrentClaimItem.ExchangeRate) > CurrentClaimItem.ActualExchangeRate)
            {
                if (((((Convert.ToDecimal(CurrentClaimItem.ExchangeRate) - CurrentClaimItem.ActualExchangeRate) / (CurrentClaimItem.ActualExchangeRate == 0 ? 1 : CurrentClaimItem.ActualExchangeRate) * 100) > 5)))
                {
                    // different more than 5%
                    StringBuilder MessageBuilder = new StringBuilder();
                    MessageBuilder.AppendLine("Exchange Rate diffrence more than 5%\n");
                    MessageBuilder.AppendLine("Actual Exchange Rate: " + Convert.ToDecimal(CurrentClaimItem.ActualExchangeRate));

                    HyperLink AlertIndicator = new HyperLink();
                    AlertIndicator.Text = Convert.ToDecimal(CurrentClaimItem.ExchangeRate).ToString();
                    AlertIndicator.CssClass = "GridViewAlertIndicator";
                    AlertIndicator.ToolTip = MessageBuilder.ToString();
                    AlertIndicator.NavigateUrl = "#";
                    AlertIndicator.Attributes["onclick"] = "alert(this.title);";

                    ItemRow.Cells[CellCounter].Controls.Add(AlertIndicator);
                }
            }
        }
        catch (Exception ex)
        {
            string LogID = SwissArmy.UniqueID();
            this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.BuiltRow] : Exception at 16. Exceed Limit Indicator : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            this.ShowErrorMessage("Error! " + LogID);

        }

        #endregion

        #region 13. Local Amount

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.AmountOut.ToString(GonzalesGeneralVariables.CurrencyFormat);
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 14. Having Receipts

        Image ImageHavingReceipts = new Image();
        ImageHavingReceipts.ImageUrl = (CurrentClaimItem.HavingReceipts) ? GonzalesImages.Icon_Checked : GonzalesImages.Icon_Crossed;
        
        CellCounter++;
        ItemRow.Cells[CellCounter].Controls.Add(ImageHavingReceipts);
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 15. Project ID

        CellCounter++;
        ItemRow.Cells[CellCounter].Text = CurrentClaimItem.ProjectID;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 16. Popout Detail

        HiddenField HiddenPopOut = new HiddenField();
        HiddenPopOut.ID = CurrentClaimItem.InternalID + "_HiddenPopOut";
        HiddenPopOut.Value = "0"; // default

        HiddenField HiddenAlreadySeen = new HiddenField();
        HiddenAlreadySeen.ID = CurrentClaimItem.InternalID + "_HiddenAlreadySeen";
        HiddenAlreadySeen.Value = "0";

        HiddenField HiddenGLCode = new HiddenField();
        HiddenGLCode.ID = CurrentClaimItem.InternalID + "_HiddenGLCode";
        HiddenGLCode.Value = CurrentClaimItem.ClaimType.GLCode;

        ImageButton ImageButtonDetail = new ImageButton();
        ImageButtonDetail.ID = CurrentClaimItem.InternalID + "_ImageButtonDetail";
        ImageButtonDetail.ImageUrl = GonzalesImages.Icon_Detail;
        ImageButtonDetail.Attributes["onclick"] = "ShowSpecialPopOut('" + CurrentClaimItem.ClaimType.GLCode + "', null, 'NoEdit=1&id=" + this.ClaimInternalID + "&did=" + CurrentClaimItem.InternalID + "&remarks=" + CurrentClaimItem.Remarks.Replace("'", "#") + "'); document.getElementById('" + CurrentClaimItem.InternalID + "_HiddenAlreadySeen').value = 1;return false;";

        CellCounter++;
        ItemRow.Cells[CellCounter].Controls.Add(HiddenPopOut);
        ItemRow.Cells[CellCounter].Controls.Add(ImageButtonDetail);
        ItemRow.Cells[CellCounter].Controls.Add(HiddenAlreadySeen);
        ItemRow.Cells[CellCounter].Controls.Add(HiddenGLCode);
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 17. Exceed Limit Indicator

        CellCounter++;

        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 18. Approval

        CheckBox CheckBoxApproverState = new CheckBox();
        CheckBoxApproverState.ID = ItemRow.ID + "_AuthorizerState";
        CheckBoxApproverState.Attributes["onclick"] = "document.getElementById('" + ItemRow.ID + "_AuthorizerRemarks').value = (this.checked)?'':document.getElementById('" + ItemRow.ID + "_AuthorizerRemarks').value;";
        CheckBoxApproverState.Checked = true;

        HiddenField HiddenFieldWeekInYear = new HiddenField();
        HiddenFieldWeekInYear.Value = CurrentClaimItem.WeekInYear.ToString();

        HiddenField HiddenFieldOriginalOrder = new HiddenField();
        HiddenFieldOriginalOrder.Value = CurrentClaimItem.Order.ToString();

        CellCounter++;
        ItemRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        ItemRow.Cells[CellCounter].Controls.Add(CheckBoxApproverState);
        ItemRow.Cells[CellCounter].Controls.Add(HiddenFieldWeekInYear);
        ItemRow.Cells[CellCounter].Controls.Add(HiddenFieldOriginalOrder);        

        #endregion

        #region 19. Authorizer Remarks

        TextBox TextBoxAuthorizerRemarks = new TextBox();
        TextBoxAuthorizerRemarks.ID = ItemRow.ID + "_AuthorizerRemarks";
        TextBoxAuthorizerRemarks.CssClass = "DetailGridTextBox";
        TextBoxAuthorizerRemarks.Width = Unit.Percentage(90);
        TextBoxAuthorizerRemarks.Attributes["OnChange"] = "this.title = this.value;";

        CellCounter++;
        ItemRow.Cells[CellCounter].Controls.Add(TextBoxAuthorizerRemarks);

        #endregion

        //Added by Agnes for Total Personal Expenses
        if (CurrentClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard && CurrentClaimItem.IsPersonnal)
            TotalPersonalExpenses -= CurrentClaimItem.AmountOut;
        // final
        this.Table_ClaimDetailGrid.Rows.Add(ItemRow);
    }

    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData

    public void LoadData()
    {
        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            this.ResultObj = CurClaimManager.GetClaimByInternalID(this.ClaimInternalID);

            if (this.ResultObj.Status == GonzalesClaimHeader.TypeOfClaimStatus.PendingForAuthorize && this.ResultObj.NextAuthorizer.InternalID.CompareTo(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID) == 0)
            {

                if (this.ResultObj != null)
                {
                    //Added By Agnes[09 April 2009] - For Enhancement to enabled/disabled the PrinterFriendlyNameList
                    //if (this.ResultObj.Category == CategoryOfClaim.Entertainment)
                    //    this.Button_PrinterFriendlyNameList.Visible = true;

                    // get user
                    using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                    {
                        SystemUser Claimant = CurUserManager.GetUserByInternalID(this.ResultObj.ClaimedBy.InternalID);

                        this.ResultObj.ClaimedBy = Claimant;
                    }

                    this.ResultObj.ClaimDetails = CurClaimManager.GetClaimItemsByClaimHeaderInLangWithWeeklyLmit(this.ClaimInternalID, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage, this.ResultObj.ClaimedBy.InternalID);
                }
                else
                {
                    this.CurLogManager.LogError("[GonzalesClaimsPendingForApprovalDetail.LoadData] : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                }
            }
            else
            {
                // wrong status, could be already change, no longer valid
                Server.Transfer("GonzalesViewClaim.aspx?id=" + this.ClaimInternalID);
            }
        }

        #region Supporting Documents

        using (FileManager CurFileManager = new FileManager(this.CurrentPrivateSession))
        {
            SupportingDocuments ListOfDocs = CurFileManager.GetFilesByClaimID(this.ClaimInternalID);
            if (ListOfDocs != null)
            {
                if (this.Button_FileManager.Text.IndexOf("(") <= 0)
                {
                    this.Button_FileManager.Text += " (" + ListOfDocs.Count + ")";
                }
            }
            else
            {
                if (this.Button_FileManager.Text.IndexOf("(") <= 0)
                {
                    this.Button_FileManager.Text += " (0)";
                }

                string ErrorID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(ErrorID, "[GonzalesMyClaimDetail.LoadData] : Failed at CurFileManager.GetFilesByClaimID(" + this.ClaimInternalID + ") : " + CurFileManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }
        }

        #endregion
    }

    #endregion

    #region FillInData
    protected void FillInData()
    {
        this.LabelValue_ClaimNo.Text = this.ResultObj.ClaimID;
        this.LabelValue_CreationDate.Text = SwissArmy.DateConvert(this.ResultObj.CreatedOn, this.CurrentPrivateSession.DateFormatInUse, "/");
        this.LabelValue_SubmissionDate.Text = SwissArmy.DateConvert(this.ResultObj.SubmittedOn, this.CurrentPrivateSession.DateFormatInUse, "/");
        this.LabelValue_EmployeeName.Text = this.ResultObj.ClaimedBy.DisplayName + "(" + this.ResultObj.ClaimedBy.EmailID + ")"; ;
        this.LabelValue_EmployeeNo.Text = this.ResultObj.ClaimedBy.EmployeeID;
        this.LabelValue_Purpose.Text = this.ResultObj.Reasons;
        this.LabelValue_ProfitCenter.Text = this.ResultObj.ClaimedBy.CostCenter;
        this.LabelValue_Category.Text = ClaimManager.GetClaimCategoryInString(this.ResultObj.Category);
        if (this.ResultObj.ProjectedOn != DateTime.MinValue)
            this.LabelValue_ClaimPeriod.Text = this.ResultObj.ProjectedOn.ToString("MMMM") + " " + this.ResultObj.ProjectedOn.Year.ToString();


        this.Label_TotalAmount.Text += " (" + this.ResultObj.LocalCurrency.InternalID + ")";
        this.Label_TotalLocalAmount.Text = this.ResultObj.TotalClaimedAmount.ToString(GonzalesGeneralVariables.CurrencyFormat);
        this.Label_TotalAmountAlreadyPaid.Text = this.ResultObj.TotalLocalAmountAlreadyPaid.ToString(GonzalesGeneralVariables.CurrencyFormat);
        this.Label_Owning.Text = this.ResultObj.TotalLocalActualAmountLeft.ToString(GonzalesGeneralVariables.CurrencyFormat);

        if (this.ResultObj.ChequeNo.Length > 0)
        {
            this.Table_ChequeInfo.Visible = true;
            this.LabelValue_ChequeNo.Text = this.ResultObj.ChequeNo;
            this.LabelValue_IssuedBank.Text = this.ResultObj.ChequeIssuesBank;
        }

        this.ImageButton_Mail.ToolTip = "Send an email to " + this.ResultObj.ClaimedBy.DisplayName;
        this.ImageButton_Mail.Attributes["onclick"] = "document.location = 'mailto:" + this.ResultObj.ClaimedBy.Email + "?subject=[" + GonzalesGeneralVariables.WebsiteName + "] Enquiry: " + this.ResultObj.ClaimID + "'; return false;";


    }
    #endregion

    #region PolicyEnvironmentSetup (Not using)

    protected void PolicyEnvironmentSetupX()
    {
        this.WeeklySpentPolicies = new WeeklyTotalSpentPolicies();

        if (this.ResultObj != null)
        {
            for (int x = 0; x < this.ResultObj.ClaimDetails.Count; x++)
            {
                GonzalesClaimItemWithWeeklyLimit CurClaimItem = (GonzalesClaimItemWithWeeklyLimit)this.ResultObj.ClaimDetails[x];

                // now, collect policy
                bool PolicyMatched = false;
                foreach (WeeklyTotalSpentPolicy CurrentPolicy in this.WeeklySpentPolicies)
                {
                    PolicyMatched = false;

                    if ((PolicyMatched = (CurrentPolicy.WeekInYear == CurClaimItem.WeekInYear)))
                    {
                        break;
                    }
                }

                if (!PolicyMatched)
                {
                    this.WeeklySpentPolicies.Add(new WeeklyTotalSpentPolicy(CurClaimItem.WeekInYear, CurClaimItem.TotalSpentInWeek));
                }
            }
        }
    }

    protected void PolicyEnvironmentSetup()
    {
        if (this.ResultObj != null)
        {
            using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
            {
                ClaimTypeLimitPolicies PolicyCollections = null;
                if ((PolicyCollections = CurClaimManager.GetClaimItemLimitPolicies((SystemUser)this.ResultObj.ClaimedBy, this.ResultObj.InternalID)) != null)
                {
                    this.DataValidateByPolicy(PolicyCollections);
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.PolicyEnvironmentSetup] : Failed at CurClaimManager.GetClaimItemLimitPolicies() : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }
        }
    }

    #endregion

    #region DataValidateByPolicy (Not using)
    
    public void DataValidateByPolicyX()
    {
        // compare by policy
        // this policy will go by every single row
        
        bool IsExceedLimit = false;
        Authoriser CurrentAuthorizer = null;

        // get the ownself min and max limit
        using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
        {
            CurrentAuthorizer = CurUserManager.GetAuthorizerByID(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);

            if (CurrentAuthorizer == null)
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForAuthorizedDetail.DataValidateByPolicy] : Failed at CurUserManager.GetAuthorizerByID('" + this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage("Error! " + LogID);
            }
        }

        if (CurrentAuthorizer != null)
        {
            MasterBaseCollection CurrencyCollection = null;

            // diff currency, need to convert
            using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
            {
                CurrencyCollection = CurCurrencyManager.GetLatestExchangeRate(this.ResultObj.LocalCurrency);
            }

            for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
            {
                decimal TotalClaimed = 0;
                IsExceedLimit = false;
                int WeekInYear = Int32.Parse(((HiddenField)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[1]).Value);

                decimal MinLimitInLocal = 0;
                for (int y = 0; y < CurrencyCollection.Count; y++)
                {
                    Currency CurCurrency = (Currency)CurrencyCollection[y];

                    if (CurCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                    {
                        MinLimitInLocal = CurrentAuthorizer.MinLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());                        
                        break;
                    }
                }

                for (int y = 0; y < this.WeeklySpentPolicies.Count; y++)
                {
                    if (WeekInYear == this.WeeklySpentPolicies[y].WeekInYear)
                    {
                        TotalClaimed = this.WeeklySpentPolicies[y].TotalSpentInWeek;
                        if (this.WeeklySpentPolicies[y].TotalSpentInWeek > MinLimitInLocal)
                        {
                            IsExceedLimit = true;
                            break;
                        }
                    }
                }

                if (IsExceedLimit)
                {
                    CheckBox CheckBoxApproval = (CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0];
                    CheckBoxApproval.Checked = false;

                    StringBuilder MessageBuilder = new StringBuilder();
                    MessageBuilder.Append("Exceed weekly limit\n");
                    MessageBuilder.Append("Week in year: " + WeekInYear + "\n");
                    MessageBuilder.Append("Total claimed: " + this.ResultObj.LocalCurrency.InternalID + " " + TotalClaimed + "\n");                    

                    Image ImageExceedLimit = new Image();
                    ImageExceedLimit.ImageUrl = GonzalesImages.Icon_Warning;
                    ImageExceedLimit.ToolTip = MessageBuilder.ToString();
                    ImageExceedLimit.Attributes["onclick"] = ("alert(this.title);");

                    this.Table_ClaimDetailGrid.Rows[x].Cells[17].Controls.Add(ImageExceedLimit);
                }
            }
        }
    }

    public void DataValidateByPolicy(ClaimTypeLimitPolicies LimitPolicy)
    {
        // compare by policy
        // this policy will go by every single row
        for (int x = 0; x < LimitPolicy.Count; x++)
        {
            bool IsExceedLimit = false;
            string ClaimDetailRemarks = "";

            // get the description, to check if this is a entertainment
            for (int y = 1; y < this.Table_ClaimDetailGrid.Rows.Count; y++)
            {
                if (this.Table_ClaimDetailGrid.Rows[y].UniqueID.CompareTo(LimitPolicy[x].ClaimDetalID) == 0)
                {
                    ClaimDetailRemarks = this.Table_ClaimDetailGrid.Rows[y].Cells[8].Text;
                    break;
                }
            }

            // check the currency if it is the same
            // if not same, muz convert the currency first
            if (LimitPolicy[x].LimitCurrency.InternalID.CompareTo(LimitPolicy[x].LocalCurrency.InternalID) == 0)
            {
                // same currency
                if (ClaimDetailRemarks.IndexOf("[ENT]") == 0)
                {
                    string[] RemarksArray = SwissArmy.StringSplit(ClaimDetailRemarks, ",");
                    int TotaParticipants = Convert.ToInt32(RemarksArray[1]);
                    decimal TotalCostPerHead = (LimitPolicy[x].TotalClaimedInPeriod / TotaParticipants);

                    IsExceedLimit = (TotalCostPerHead > LimitPolicy[x].LimitAmount);
                }
                else
                {
                    IsExceedLimit = (LimitPolicy[x].TotalClaimedInPeriod > LimitPolicy[x].LimitAmount);
                }
            }
            else
            {
                if (ClaimDetailRemarks.IndexOf("[ENT]") == 0)
                {
                    string[] RemarksArray = SwissArmy.StringSplit(ClaimDetailRemarks, ",");
                    int TotaParticipants = Convert.ToInt32(RemarksArray[1]);
                    decimal TotalCostPerHead = (LimitPolicy[x].TotalClaimedInPeriod / TotaParticipants);

                    IsExceedLimit = ((TotalCostPerHead * LimitPolicy[x].ExRateFigure) > LimitPolicy[x].LimitAmount);

                }
                else
                {
                    IsExceedLimit = ((LimitPolicy[x].TotalClaimedInPeriod * LimitPolicy[x].ExRateFigure) > LimitPolicy[x].LimitAmount);
                }
            }

            // exceed limit, muz do something
            if (IsExceedLimit)
            {
                for (int y = 1; y < this.Table_ClaimDetailGrid.Rows.Count; y++)
                {
                    if (this.Table_ClaimDetailGrid.Rows[y].ID.CompareTo(LimitPolicy[x].ClaimDetalID) == 0)
                    {

                        StringBuilder MessageBuilder = new StringBuilder("");
                        MessageBuilder.Append("Alert: Exceed Limit\n");
                        MessageBuilder.Append("Duration: " + ClaimManager.GetClaimTypeLimitDurationInString(LimitPolicy[x].Duration) + "\n");
                        MessageBuilder.Append("Approved Limit: " + LimitPolicy[x].LimitCurrency.DisplayName + " " + LimitPolicy[x].LimitAmount + "\n");

                        Image ImageExceedLimit = new Image();
                        ImageExceedLimit.ImageUrl = GonzalesImages.Icon_Warning;
                        ImageExceedLimit.ToolTip = MessageBuilder.ToString();
                        ImageExceedLimit.Attributes["onclick"] = "alert(this.title)";

                        this.Table_ClaimDetailGrid.Rows[y].Cells[17].Controls.Add(ImageExceedLimit);
                        this.Table_ClaimDetailGrid.Rows[y].Cells[17].HorizontalAlign = HorizontalAlign.Center;


                        break;
                    }
                }
            } // if exceed limit
        }

        // check the checkbox that no need to check
        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            //if (this.Table_ClaimDetailGrid.Rows[x].Cells[16].Controls.Count == 0)
            {
                ((CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0]).Checked = true;
            }
        }
    }

    #endregion

    #region DataValidate

    protected bool DataValidate(string status)
    {
        bool smooth = true;
        StringBuilder MessageBuilder = new StringBuilder("<ul>");
        
        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            CheckBox CurrentCheckBox = (CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0];
            TextBox CurrentTextBox = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[19].Controls[0];

            if (status.CompareTo("approved") != 0)
            {
                /*
                if (!CurrentCheckBox.Checked && CurrentTextBox.Text.Trim().Length == 0)
                {
                    // un-checked but no remarks
                    MessageBuilder.AppendLine("<li>Please enter remarks for item #" + x + ", as this item is not been approved by you.</li>");
                    smooth = false;
                }
                */
                if (CurrentTextBox.Text.Length > 0)
                {
                    smooth = true;
                    break;
                }
                else
                {
                    if (MessageBuilder.ToString().Length < 10)
                    {
                        MessageBuilder.AppendLine("<li>" + this.MandatoryMessage + "</li>");
                        smooth = false;
                    }
                }
            }
            else
            {
                if (!CurrentCheckBox.Checked)
                {
                    MessageBuilder.AppendLine("<li>" + this.WarningMessage1 + x + this.WarningMessage2 +"</li>");
                    smooth = false;
                }
            }

            this.IsApprove = (!CurrentCheckBox.Checked) ? false : this.IsApprove;
        }
        

        MessageBuilder.AppendLine("</ul>");

        if (!smooth)
        {
            this.ShowErrorMessage(MessageBuilder.ToString());
        }

        return smooth;

    }

    #endregion

    #region DataCollect

    public void DataCollect()
    {
        if (this.ResultObj != null)
        {
            for (int x = 0; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
            {
                for (int y = 0; y < this.ResultObj.ClaimDetails.Count; y++)
                {
                    if (this.ResultObj.ClaimDetails[y].InternalID.CompareTo(this.Table_ClaimDetailGrid.Rows[x].ID) == 0)
                    {
                        GonzalesClaimItem CurrentItem = (GonzalesClaimItem)this.ResultObj.ClaimDetails[y];

                        CurrentItem.AuthorizerState = ((CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0]).Checked;
                        CurrentItem.AuthorizerRemarks = ((TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[19].Controls[0]).Text;

                        break;
                    }
                }
            }
        }
    }

    #endregion

    #region SaveData

    protected bool SaveData()
    {
        bool smooth = true;

        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            if (!(smooth = CurClaimManager.UpdateClaimByAuthorizer(this.ResultObj)))
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForAuthorizedDetail.SaveData] : Failed at CurClaimManager.UpdateClaimByAuthorizer : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage("error: " + LogID);
            }
        }

        return smooth;
    }

    #endregion

    #region ShadowUserPolicy
    protected void ShadowUserPolicy()
    {
        if (this.CurrentPrivateSession.ShadowMode)
        {
            if (this.CurrentPrivateSession.CurrentLoggedOnUser.ReviewOnBehalfBy != null &&
                this.CurrentPrivateSession.CurrentLoggedOnUser.ReviewOnBehalfBy.InternalID.CompareTo(this.CurrentPrivateSession.ShadowUser.InternalID) == 0)
            {
                // shadow user can't do any action
                this.Button_Approve.Visible = this.Button_Reject.Visible = false;
            }

        }
    }
    #endregion

    #endregion

}
